package com.jpf.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.jpf.demo.Goods;
import com.jpf.demo.Page;
import com.jpf.service.GoodsService;
@MultipartConfig
@WebServlet("/AddGoods.do")
public class AddGoods extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String cid = request.getParameter("cid");
		String gname = request.getParameter("gname");
		String brand = request.getParameter("brand");
		String content = request.getParameter("content");
		String shelftime = request.getParameter("shelftime");
		String gprice = request.getParameter("gprice");
		String gstock = request.getParameter("gstock");
		
		//文件上传
		Part part = request.getPart("gimage");
        String disposition = part.getHeader("Content-Disposition");
        String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
          //随机的生存一个32的字符串+文件名
        String filename = UUID.randomUUID()+suffix;
   //     String filename = "gimage"+suffix;
          //获取上传的文件名
        InputStream is = part.getInputStream();
        //动态获取服务器的路径
        //将图片保存到E:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\pcshop\\upload中。
        //服务器存放图片，数据库存放图片名
        String serverpath = request.getServletContext().getRealPath("goodsimage");
      
        FileOutputStream fos = new FileOutputStream(serverpath+"/"+filename);
       
        byte[] bty = new byte[1024];
        int length =0;
        while((length=is.read(bty))!=-1){
            fos.write(bty,0,length);
        }
        fos.close();
        is.close();
		if(cid.equals("")||gname.equals("")||brand.equals("")||content.equals("")||shelftime.equals("")||gprice.equals("")||gstock.equals("")) {
			request.getSession().setAttribute("message", "添加失败，请重新填写！");
			response.sendRedirect("admin/add.jsp");
		}else {
			Goods goods = new Goods(cid, gname, brand,filename, content, shelftime, Double.parseDouble(gprice), Integer.parseInt(gstock));
			GoodsService goodsService = new GoodsService();
			if(goodsService.insert(goods))
				response.sendRedirect("QueryGoods.do");
			else response.sendRedirect("admin/error.jsp");
		}
		
	}
}
